from datetime import datetime
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import warnings

# 忽略警告
warnings.filterwarnings("ignore")
# 显示中文
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

# RFM模型分析
# 数据初步处理
data = pd.read_csv(r'..\taobao\data\taobao_1.csv')
print(data)
data['用户名'] = data['用户名'].astype('str')
data['日期'] = pd.to_datetime(data['日期'], format='%Y-%m-%d')
data = data[data['行为'] == 4][['用户名', '行为', '日期']]
data.sort_values(by='用户名', inplace=True, )
print(data.info())
print(data)
# R
R = data.groupby('用户名')['日期'].max().reset_index()
R['R'] = (pd.to_datetime('2014-12-29') - R['日期']).dt.days
R = R[['用户名', 'R']].rename(columns={'R': 'R(时间差)'})
print(R)
# F
F = data.groupby('用户名')['日期'].count().reset_index().rename(columns={'日期': 'F(购买次数)'})
print(F)
RFM = pd.merge(R, F, on="用户名")
print(RFM)
print(RFM.dtypes)
for i in ["R(时间差)", "F(购买次数)"]:
    RFM[i] = RFM[i].astype(float)
# 计算R、F、M值
R_mean = RFM['R(时间差)'].mean()
F_mean = RFM['F(购买次数)'].mean()

RFM["r"] = np.where(RFM["R(时间差)"] > R_mean, "高", "低")
RFM["f"] = np.where(RFM["F(购买次数)"] > F_mean, "高", "低")
RFM["标签"] = RFM["r"].str[:] + RFM["f"].str[:]
print(RFM.head())
print(RFM.dtypes)
# 缺少用户消费金额，暂不考虑M值

def trans_labels(x):
    if x == "高高":
        return "重要价值客户"
    elif x == "低高":
        return "重要唤回客户"
    elif x == "高低":
        return "重要深耕客户"
    else:
        return "重要挽回客户"


RFM['标签'] = RFM['标签'].apply(trans_labels)
print(RFM)
print(RFM['标签'].value_counts())

try:
    RFM.to_csv(r'..\taobao\data\user_RFM.csv', encoding="utf_8_sig")
except:
    pass
